//
//  Int+SGExtension.swift
//  QingLiuSwift
//
//  Created by xyanl on 2024/11/14.
//  Copyright © 2024 考拉🐨. All rights reserved.
//


import UIKit

extension Int: SpadgerCompatible {}

extension Int {
    var toBool: Bool {
        self > 0
    }
}

// MARK: - 基本的扩展方法
public extension Spadger where Base == Int {
    
    /// 是否是偶数
    /// - Returns: 结果
    func isEven() -> Bool {
        base % 2 == 0
    }
    
    ///  取区间内的随机数，如取  0..<10 之间的随机数
    /// - Parameter within: 0..<10
    /// - Returns: 返回区间内的随机数
    static func random(within: Range<Int>) -> Int {
        let delta = within.upperBound - within.lowerBound
        return within.lowerBound + Int(arc4random_uniform(UInt32(delta)))
    }
}

// MARK: - 转换为其他单位
public extension Spadger where Base == Int {
    /// 转换万单位
    /// - Parameters:
    ///   - scale: 小数点后舍入值的位数，默认 1 位
    ///   - roundingMode: 小数取舍方式
    ///   - unit: 单位
    ///   - isNeedAddZero: 是否后面追加0，比如：1.201  保留2位是：1.20 或者 1.2，如果设置为true，则scale是几位则后面是几位，不足的使用0填充
    /// - Returns: 转换后的结果
    func toTenThousandString(scale: Int16 = 1, roundingMode: NSDecimalNumber.RoundingMode = .plain, unit: String = "万", isNeedAddZero: Bool = false) -> String {
        let absValue = abs(base)
        if absValue <= 9999 {
            return "\(base)"
        }
        
        let decimalValue = String(base).sg.dividing("10000").sg.decimal(roundingMode, scale: scale)
        return (isNeedAddZero ? "\(String(format: "%.\(scale)f", decimalValue.sg.toDouble))" : "\(decimalValue)") + unit
    }
    

    /// 转换为大小单位：UInt64 -> "bytes", "KB", "MB", "GB", "TB", "PB",  "EB",  "ZB", "YB"
    /// - Parameter size: 大小
    /// - Returns: 转换后的文件大小
    func covertUInt64ToString() -> String {
        var convertedValue: Double = Double(base)
        var multiplyFactor = 0
        let tokens = ["bytes", "KB", "MB", "GB", "TB", "PB",  "EB",  "ZB", "YB"]
        while convertedValue > 1024 {
            convertedValue /= 1024
            multiplyFactor += 1
        }
        return String(format: "%4.2f %@", convertedValue, tokens[multiplyFactor])
    }
}
